<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能设备控制中心</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .device-card {
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
            height: 100%;
        }
        .device-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .device-on {
            background-color: #e3f2fd;
            border-color: #90caf9;
        }
        .device-off {
            background-color: #f5f5f5;
        }
        .card-header {
            font-weight: bold;
        }
        .energy-display {
            font-size: 1.5rem;
            font-weight: bold;
            color: #2196f3;
        }
        .status-badge {
            font-size: 0.9rem;
        }
        .nav-link {
            color: #495057;
        }
        .nav-link.active {
            color: #0d6efd;
            font-weight: bold;
        }
        .suggestion-card {
            border-left: 4px solid #28a745;
        }
        .room-dropdown {
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm mb-4">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fa fa-home mr-2"></i>智能设备控制中心
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/devices">设备</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/scenes">场景</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/schedules">定时任务</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/analytics">数据分析</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <!-- 当前系统状态 -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-4">
                                <i class="fa fa-bolt fa-3x"></i>
                            </div>
                            <div class="col-8 text-right">
                                <p class="card-text">当前功耗</p>
                                <p class="energy-display">{{ total_power }} kW</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-4">
                                <i class="fa fa-thermometer-half fa-3x"></i>
                            </div>
                            <div class="col-8 text-right">
                                <p class="card-text">当前温度</p>
                                <p class="energy-display">{{ system_status.temperatures[0] }}°C</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-4">
                                <i class="fa fa-tint fa-3x"></i>
                            </div>
                            <div class="col-8 text-right">
                                <p class="card-text">当前湿度</p>
                                <p class="energy-display">{{ system_status.humidities[0] }}%</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 智能建议 -->
        {% if smart_suggestions %}
        <div class="row mb-4">
            <div class="col">
                <h3 class="mb-3"><i class="fa fa-lightbulb-o text-warning"></i> 智能建议</h3>
                <div class="row">
                    {% for suggestion in smart_suggestions %}
                    <div class="col-md-4 mb-3">
                        <div class="card suggestion-card">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-3">
                                        <span class="badge bg-success status-badge">{{ suggestion.confidence }}%</span>
                                    </div>
                                    <div class="col-9">
                                        <h5 class="card-title">{{ suggestion.device_name }}</h5>
                                        <p class="card-text text-sm">{{ suggestion.reason }}</p>
                                        <button class="btn btn-sm btn-primary" onclick="toggleDevice({{ suggestion.device_id }}, {{ 'true' if suggestion.suggested_action == '开启' else 'false' }})">{{ suggestion.suggested_action }}</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}

        <!-- 房间选择器 -->
        <div class="row mb-4 room-dropdown">
            <div class="col">
                <select class="form-select" id="room-selector" onchange="location = '/rooms/' + this.value;">
                    <option value="">所有房间</option>
                    {% for room in rooms %}
                    <option value="{{ room }}">{{ room }}</option>
                    {% endfor %}
                </select>
            </div>
        </div>

        <!-- 设备列表 -->
        <div class="row">
            {% for device in device_config %}
            <div class="col-md-3 mb-4">
                <div class="card device-card {{ 'device-on' if system_status.relays[device.id-1] else 'device-off' }}" onclick="toggleDevice({{ device.id }})">
                    <div class="card-header">
                        <i class="fa fa-{{ device.icon }}"></i> {{ device.name }}
                        <span class="float-right badge {{ 'bg-success' if system_status.relays[device.id-1] else 'bg-secondary' }}">
                            {{ '开启' if system_status.relays[device.id-1] else '关闭' }}
                        </span>
                    </div>
                    <div class="card-body">
                        <p class="card-text">{{ device.room }}</p>
                        <p class="card-text text-sm text-muted">{{ device.type }}</p>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>

        <!-- 常用场景 -->
        <div class="row mt-6">
            <div class="col">
                <h3 class="mb-3"><i class="fa fa-magic text-primary"></i> 常用场景</h3>
                <div class="row">
                    {% for scene in scene_config %}
                    <div class="col-md-3 mb-4">
                        <div class="card bg-light" onclick="activateScene({{ scene.id }})">
                            <div class="card-body text-center">
                                <i class="fa fa-{{ scene.icon }} fa-3x text-primary mb-2"></i>
                                <h5 class="card-title">{{ scene.name }}</h5>
                                <p class="card-text text-sm">{{ scene.description }}</p>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- 实时数据图表 -->
        <div class="row mt-6">
            <div class="col-md-6 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h4><i class="fa fa-line-chart text-info"></i> 温度变化</h4>
                    </div>
                    <div class="card-body">
                        <canvas id="temperatureChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-6 mb-4">
                <div class="card">
                    <div class="card-header">
                        <h4><i class="fa fa-tint text-primary"></i> 湿度变化</h4>
                    </div>
                    <div class="card-body">
                        <canvas id="humidityChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 切换设备状态
        function toggleDevice(deviceId, state = null) {
            // 发送请求
            fetch('/api/toggle_relay', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    device_id: deviceId,
                    state: state !== null ? state : undefined
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 刷新页面
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败');
            });
        }
        
        // 激活场景
        function activateScene(sceneId) {
            fetch('/api/activate_scene', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ scene_id: sceneId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示成功消息
                    alert('场景激活成功');
                    // 延迟刷新页面，等待设备状态更新
                    setTimeout(() => location.reload(), 1000);
                } else {
                    alert('场景激活失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败');
            });
        }
        
        // 定时更新系统状态
        function updateSystemStatus() {
            fetch('/api/get_status')
            .then(response => response.json())
            .then(data => {
                // 更新设备状态
                for (let i = 0; i < 8; i++) {
                    const deviceId = i + 1;
                    // 使用标准的查询方式查找设备卡片
                    const deviceCards = document.querySelectorAll('.device-card');
                    for (let card of deviceCards) {
                        const headerText = card.querySelector('.card-header').textContent;
                        if (headerText.includes(deviceId.toString())) {
                            const badge = card.querySelector('.badge');
                            if (badge) {
                                if (data.relays[i]) {
                                    badge.className = 'float-right badge bg-success';
                                    badge.textContent = '开启';
                                    card.className = 'card device-card device-on';
                                } else {
                                    badge.className = 'float-right badge bg-secondary';
                                    badge.textContent = '关闭';
                                    card.className = 'card device-card device-off';
                                }
                            }
                            break;
                        }
                    }
                }
            })
            .catch(error => console.error('Error updating status:', error));
        }
        
        // 定时更新（每5秒）
        setInterval(updateSystemStatus, 5000);
        
        // 初始化图表
        document.addEventListener('DOMContentLoaded', function() {
            // 获取环境数据
            fetch('/api/get_environment_data')
            .then(response => response.json())
            .then(data => {
                // 温度图表
                const tempCtx = document.getElementById('temperatureChart').getContext('2d');
                const tempChart = new Chart(tempCtx, {
                    type: 'line',
                    data: {
                        labels: data.hours,
                        datasets: [
                            {
                                label: '客厅温度',
                                data: data.temperature1,
                                borderColor: 'rgba(255, 99, 132, 1)',
                                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                                tension: 0.3
                            },
                            {
                                label: '卧室温度',
                                data: data.temperature2,
                                borderColor: 'rgba(54, 162, 235, 1)',
                                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                                tension: 0.3
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: {
                                position: 'top',
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: false,
                                min: 10,
                                max: 40
                            }
                        }
                    }
                });
                
                // 湿度图表
                const humidityCtx = document.getElementById('humidityChart').getContext('2d');
                const humidityChart = new Chart(humidityCtx, {
                    type: 'line',
                    data: {
                        labels: data.hours,
                        datasets: [
                            {
                                label: '客厅湿度',
                                data: data.humidity1,
                                borderColor: 'rgba(75, 192, 192, 1)',
                                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                                tension: 0.3
                            },
                            {
                                label: '卧室湿度',
                                data: data.humidity2,
                                borderColor: 'rgba(153, 102, 255, 1)',
                                backgroundColor: 'rgba(153, 102, 255, 0.2)',
                                tension: 0.3
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: {
                                position: 'top',
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: false,
                                min: 20,
                                max: 90
                            }
                        }
                    }
                });
            })
            .catch(error => console.error('Error loading chart data:', error));
        });
    </script>
</body>
</html>